package com.ruoyi.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.basic.service.IBaseService;
import com.common.util.ListConvertMap;
import com.common.util.MergeDataSource;
import com.param.impl.UpdatePaymentParam;
import com.ruoyi.center.service.INoticeCenterService;
import com.ruoyi.change.pay.IPayStatus;
import com.ruoyi.change.pay.context.PayStatusContext;
import com.ruoyi.change.pay.factory.PayStatusFactory;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.pay.manager.domain.PayManager;
import com.ruoyi.pay.manager.service.IPayManagerService;
import com.ruoyi.team.service.ITeamInformationService;
import com.ruoyi.user.domain.MgUser;
import com.ruoyi.user.service.IMgUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.configuration.service.IMgTeamSigningRewardsService;
import com.ruoyi.manager.service.IMgServiceManagerService;
import com.ruoyi.order.domain.MgOrder;
import com.ruoyi.order.service.IMgOrderService;
import com.ruoyi.order.service.IOrderLogService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 支付管理Controller
 * 
 * @author ruoyi
 * @date 2023-12-22
 */
@RestController
@RequestMapping("/pay/manager")
public class PayManagerController extends BaseController {
	private IPayManagerService payManagerService;

	IMgUserService userService;

	IOrderLogService orderLogService;

	IMgServiceManagerService serviceManager;
	
	ITeamInformationService teamInformationService;

	IMgTeamSigningRewardsService mgTeamSigningRewardsService;
	
	INoticeCenterService noticeCenterService;
	
	@Resource
    public void setNoticeCenterService(INoticeCenterService noticeCenterService) {
        this.noticeCenterService = noticeCenterService;
    }
	
	@Resource
    public void setTeamInformationService(ITeamInformationService teamInformationService) {
        this.teamInformationService = teamInformationService;
    }
	
	@Resource
    public void setMgTeamSigningRewardsService(
            IMgTeamSigningRewardsService mgTeamSigningRewardsService) {
        this.mgTeamSigningRewardsService = mgTeamSigningRewardsService;
    }

	@Resource
	public void setOrderLogService(IOrderLogService orderLogService) {
		this.orderLogService = orderLogService;
	}

	@Resource
	public void setServiceManager(IMgServiceManagerService serviceManager) {
		this.serviceManager = serviceManager;
	}

	@Resource
	public void setPayManagerService(IPayManagerService payManagerService) {
		this.payManagerService = payManagerService;
	}

	@Resource
	public void setUserService(IMgUserService userService) {
		this.userService = userService;
	}

	public PayManagerController(IPayManagerService payManagerService) {
		this.payManagerService = payManagerService;
	}

//    private IPayManagerServiceService managerServiceService;

	private IMgOrderService orderService;

	/**
	 * 查询支付管理列表
	 */
	@PreAuthorize("@ss.hasPermi('pay:manager:list')")
	@GetMapping("/list")
	public TableDataInfo list(PayManager payManager) {
		List<PayManager> list = listData(payManager);

		return getDataTable(list);
	}

	protected List<PayManager> listData(PayManager payManager) {
		List<Integer> userIdsSearch = new ArrayList<Integer>();

		Integer userId = payManager.getUserId();

		if (null != userId) {
			userIdsSearch.add(userId);
		}

		String realname = payManager.getRealname();

		if (null != realname) {

			MgUser mgUser = new MgUser();
			mgUser.setRealname(realname);

			List<MgUser> selectMgUserList = userService.selectMgUserList(mgUser);

			if (0 == selectMgUserList.size()) {
				return new ArrayList<PayManager>(0);
			}

			if (null != selectMgUserList) {

				userIdsSearch.addAll(
						selectMgUserList.stream().mapToInt(e -> e.getId()).boxed().collect(Collectors.toList()));
			}
		}

		if (0 == userIdsSearch.size()) {
			userIdsSearch = null;
		} else {
			payManager.setUserIds(userIdsSearch);
		}

		startPage();

		List<PayManager> list = payManagerService.selectList(payManager);

		if (0 == list.size()) {
			return new ArrayList<PayManager>(0);
		}

		sourceData(list);
		return list;
	}

	protected void sourceData(List<PayManager> list) {
		long[] userIds = list.stream().mapToLong(e -> e.getUserId().longValue()).toArray();

		List<MgUser> userList = userService.getUserList(userIds);

		Map<Integer, MgUser> listToMap = ListConvertMap.listToMap(userList, MgUser::getId);

		MergeDataSource<PayManager> mergeDataSource = new MergeDataSource<PayManager>(list);
		
		
		
		List<MgOrder> selectOrderByPayManagerId = orderService.selectOrderByPayManagerId(list.stream().mapToInt(e->e.getId()).toArray());
		
		mergeDataSource.mergeRelease(PayManager::getId, ListConvertMap.listToMapList(selectOrderByPayManagerId, MgOrder::getPayManagerId),
                (p, o) -> {
                	for (MgOrder item : o) {
						
                		if (1 == item.getUseCheckConpon()) {
                			p.setShowPayStatus((byte) 0);
                			break;
                		}
					}
                	
                    return p;
                });
		
		

		mergeDataSource.mergeRelease(PayManager::getUserId, listToMap, (p, u) -> {
			p.setRealname(u.getRealname());
			return p;
		});
	}

	/**
	 * 导出支付管理列表
	 */
	@PreAuthorize("@ss.hasPermi('pay:manager:export')")
	@Log(title = "支付管理", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, PayManager payManager) {
		List<PayManager> list = payManagerService.selectList(payManager);
		sourceData(list);

		ExcelUtil<PayManager> util = new ExcelUtil<PayManager>(PayManager.class);
		util.exportExcel(response, list, "支付管理数据");
	}

	/**
	 * 获取支付管理详细信息
	 */
	@PreAuthorize("@ss.hasPermi('pay:manager:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Integer id) {
		return success(payManagerService.selectById(id));
	}

	/**
	 * 新增支付管理
	 */
	@PreAuthorize("@ss.hasPermi('pay:manager:add')")
	@Log(title = "支付管理", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody PayManager payManager) {
		return toAjax(payManagerService.insert(payManager));
	}

	/**
	 * 修改支付管理
	 */
	@PreAuthorize("@ss.hasPermi('pay:manager:changePayment')")
	@Log(title = "支付管理", businessType = BusinessType.UPDATE)
	@PutMapping
	@Transactional
	public AjaxResult edit(@RequestBody @Valid UpdatePaymentParam payManager) {

		Integer id = payManager.getId();

		PayManager selectById = payManagerService.selectById(id);

		if (0 == selectById.getOrderStatus().compareTo(payManager.getOrderStatus())) {
			return AjaxResult.success();
		}

		IBaseService[] baseServices = new IBaseService[] { 
				this.payManagerService,
				this.orderService, 
				orderLogService,
				userService,
				mgTeamSigningRewardsService,
				teamInformationService,
				noticeCenterService
		};

		IPayStatus operationClass = PayStatusFactory.getOperationClass(payManager.getOrderStatus(), baseServices);

		PayStatusContext context = new PayStatusContext(operationClass);

		int res = context.exceute(payManager);
		
		if (-1 == res) {
			return AjaxResult.error("找不到支付管理");
		}

		// 更新子订单信息

		return toAjax(res);
	}

	/**
	 * 删除支付管理
	 */
	@PreAuthorize("@ss.hasPermi('pay:manager:remove')")
	@Log(title = "支付管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Integer[] ids) {
		return toAjax(payManagerService.deleteByIds(ids));
	}

//    @Resource
//	public void setManagerServiceService(IPayManagerServiceService managerServiceService) {
//		this.managerServiceService = managerServiceService;
//	}

	@Resource
	public void setOrderService(IMgOrderService orderService) {
		this.orderService = orderService;
	}
}
